import argparse
import logging
import time
from media import MediaScanner

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    handlers=[
        logging.StreamHandler(),  # 输出到控制台
        logging.FileHandler('media_scanner.log')  # 输出到日志文件
    ]
)
logger = logging.getLogger('Main')


def main():
    # 解析命令行参数
    parser = argparse.ArgumentParser(description="多媒体资源扫描和导入工具")
    parser.add_argument('--config', default='config.ini', help='配置文件路径')
    parser.add_argument('--test', action='store_true', help='强制启用测试模式')
    parser.add_argument('--full', action='store_true', help='强制完整执行')
    parser.add_argument('--threads', type=int, default=5, help='上传线程数（默认为5）')
    args = parser.parse_args()

    logger.info("=" * 70)
    logger.info("多媒体资源扫描导入工具")
    logger.info("=" * 70)

    scanner = None
    try:
        # 创建扫描器实例
        scanner = MediaScanner(
            base_path="",  # 从配置文件读取
            config_file=args.config
        )

        # 获取配置
        config = scanner.config
        # 确定基础路径
        base_path = config.get('scanner', {}).get('base_path', '')
        if not base_path:
            logger.error("配置文件中未指定 base_path")
            return

        scanner.scan_directory()

        # 执行上传
        upload_batch_size = int(config.get('scanner', {}).get('upload_batch_size', 2))
        max_workers = args.threads  # 使用命令行参数或默认值

        start_time = time.time()
        scanner.execute_upload_tasks(
            batch_size=upload_batch_size,
            max_workers=max_workers
        )
        elapsed_time = time.time() - start_time
        minutes, seconds = divmod(elapsed_time, 60)
        logger.info(f"上传任务总耗时: {int(minutes)}分{seconds:.2f}秒")

        # 导入数据到数据库
        if scanner.db_manager:
            if scanner.import_to_database():
                logger.info("数据库导入成功")
            else:
                logger.error("数据库导入失败")

        logger.info("\n" + "=" * 70)
        logger.info("操作完成!")
        logger.info("=" * 70)

    except Exception as e:
        logger.exception(f"处理过程中出错: {e}")
    finally:
        # 确保关闭数据库连接
        if scanner and scanner.db_manager:
            scanner.db_manager.close()
            logger.info("数据库连接已关闭")


if __name__ == "__main__":
    main()